#include "motor.h"
#include "global.h"
#include "main.h"
#include "sensorless.h"

unsigned int ADCBEMF[6]={ADC_InputCH5,ADC_InputCH4,ADC_InputCH3,ADC_InputCH5,ADC_InputCH4,ADC_InputCH3};
 

//steP,为当前步，PWM_ON_flag=1时打开PWM输出
void Commutation(unsigned int step,unsigned int PWM_ON_flag)
{	 	 
	if(PWM_ON_flag==0||MOTORSTATE==STATEERROR||MOTORSTATE==STATEERROROVER)
               { 
								 	CW_ATIM->CCR1=0;CW_ATIM->CCR2=0;CW_ATIM->CCR3=0;	
									PWM_AL_OFF;	PWM_BL_OFF;	PWM_CL_OFF;
								  CW_ATIM->CCR4=PWM_PERIOD-800;								 
									return;
							 }	 
	
  if(step==0||step==5){	PWM_AL_OFF;	PWM_CL_OFF;}//AB
  else if(step==1||step==2){	PWM_AL_OFF;	PWM_BL_OFF;	}//AC
	else if(step==3||step==4){	PWM_BL_OFF;	PWM_CL_OFF;	}//BA
	
	if(step==0||step==1){	 CW_ATIM->CCR2=0;CW_ATIM->CCR3=0;CW_ATIM->CCR1=OutPwmValue;	}
	if(step==2||step==3){	 CW_ATIM->CCR1=0;CW_ATIM->CCR3=0;CW_ATIM->CCR2=OutPwmValue;	}
	if(step==4||step==5){	 CW_ATIM->CCR1=0;CW_ATIM->CCR2=0;CW_ATIM->CCR3=OutPwmValue;	}
	
	
	if(step==0||step==5){PWM_BL_ON; }//AB
  else if(step==1||step==2){PWM_CL_ON; }// AC
	else if(step==3||step==4){PWM_AL_ON; }//BA
	
	  CW_ADC->SQRCFR_f.SQRCH0 = ADCBEMF[step]; 

	  STEP_last=step;
     
   
		Tonoroff=1;CW_ATIM->CCR4=200;
		  StepTime=BTIM_GetCounter(CW_BTIM2);
		  BTIM_SetCounter(CW_BTIM2,0); 
			 
			BTIM_SetAutoreload(CW_BTIM3,StepTime>>3);	
			
			BTIM_SetCounter(CW_BTIM3,0);
			BTIM_Cmd(CW_BTIM3, ENABLE);
			//启动退磁 
			Sta=1;//退磁状态 	
			
			HALLcount++;HALLcount1++;	  
}

void UPPWM(void)
{	
	__disable_irq(); 
	if(STEP_last==0||STEP_last==1){	 CW_ATIM->CCR2=0;CW_ATIM->CCR3=0; CW_ATIM->CCR1=OutPwmValue;	}
	if(STEP_last==2||STEP_last==3){	 CW_ATIM->CCR1=0;CW_ATIM->CCR3=0;CW_ATIM->CCR2=OutPwmValue;	}
	if(STEP_last==4||STEP_last==5){	 CW_ATIM->CCR1=0;CW_ATIM->CCR2=0;CW_ATIM->CCR3=OutPwmValue;	}
	__enable_irq();
	
		Tonoroff=1;CW_ATIM->CCR4=200;	 
}
   
void HALL_MOTOR_START(void)
{ 	
	unsigned char coun=0;				
		 
			if(MOTORSTATE==STATEERROR)return;
			HALLcount=0;  
			QDPwm=PWMMin;
			do{
				if(Sensorless_START()==0){coun++;QDPwm+=5;}		
				else break;
			}while(coun<1&&ErrorCode==0);
			if(coun>=1&&ErrorCode==0) 
					{ErrorCode=3;MOTORSTATE=STATEERROR;}	//启动失败	
	  
}
 
void MOTOR_STOP0(void)
{
	 Motor_Start_F=0; 
	 Commutation(0,0);
}


